package cn.jia.hrm.service.impl;

import cn.jia.hrm.StrUtils;
import cn.jia.hrm.VerifyCodeUtils;
import cn.jia.hrm.exception.AssertGlobal;
import cn.jia.hrm.exception.GlobalException;
import cn.jia.hrm.service.IVerifycodeService;
import cn.jia.hrm.vo.SMScode;
import cn.jia.hrm.vo.SMStoRedis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class VerifycodeServiceImpl implements IVerifycodeService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public String getimg(String key) {
        String code = StrUtils.getComplexRandomString(4);
        redisTemplate.opsForValue().set(key,code,10, TimeUnit.MINUTES);
        return VerifyCodeUtils.VerifyCode(140,40,code);
    }

    @Override
    public void sendSmsCode(SMScode smScode) {
        String imageCode = smScode.getImageCode();  //图文验证码
        String imageCodeKey = smScode.getImageCodeKey(); //UUid
        String mobile = smScode.getMobile(); //手机号

        AssertGlobal.hasText(imageCode,"图文验证码不能为空");
        AssertGlobal.hasText(imageCodeKey,"无效的key不能为空");
        AssertGlobal.hasText(mobile,"手机号不能为空");

        String codetp = (String)redisTemplate.opsForValue().get(imageCodeKey);
        AssertGlobal.hasText(codetp,"图文验证码无效");
        AssertGlobal.isEquals(imageCode,codetp,"图文验证码不匹配");

        //判断验证码是否已经发送 Date date = new Date();
        Date date = new Date();
        String smsCode=null;
        SMStoRedis firstSMS = (SMStoRedis)redisTemplate.opsForValue().get("SMS" + mobile);
        if (firstSMS !=null){
            if ((date.getTime()-firstSMS.getData()<60*1000)){
                throw  new GlobalException("操作太频繁了");
            }
            smsCode=firstSMS.getSmsCode();
        }else {
             smsCode = StrUtils.getComplexRandomString(6);  //生产随机的短信验证码
        }
        System.out.println(smsCode);
        redisTemplate.opsForValue().set("SMS"+mobile,new SMStoRedis(smsCode,date.getTime()),10,TimeUnit.MINUTES);
    }
}
